package com.CMS.client.datasource;

import java.util.List;

import com.CMS.client.UserService;
import com.CMS.client.UserServiceAsync;
import com.CMS.server.domain.User;
import com.google.gwt.core.client.GWT;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.smartgwt.client.data.DSRequest;
import com.smartgwt.client.data.DSResponse;
import com.smartgwt.client.data.Record;
import com.smartgwt.client.data.fields.DataSourceTextField;
import com.smartgwt.client.rpc.RPCResponse;
import com.smartgwt.client.widgets.form.fields.SelectItem;
import com.smartgwt.client.widgets.grid.ListGridRecord;

public class UserDataSource extends BaseDataSource{
	
	private SelectItem rolSelectItem;
	private DataSourceTextField alias = new DataSourceTextField("alias","Alias");
	private DataSourceTextField pass = new DataSourceTextField("pass","Password");
	private DataSourceTextField mail = new DataSourceTextField("mail","Mail");
	
	/*En el constructor creamos los campos que se visualizan*/
	public UserDataSource(){		
		
		rolSelectItem = new SelectItem(); 
		rolSelectItem.setOptionDataSource(new RolDataSource());
		rolSelectItem.setValueField(getId());
		rolSelectItem.setAccessKey(getId());
		rolSelectItem.setDisplayField(getDescription());
		rolSelectItem.setEmptyPickListMessage(message.messageNoRecords());
	    DataSourceTextField fieldRol = new DataSourceTextField("rol","Rol");
	    fieldRol.setEditorType(rolSelectItem);        
	    
		addField(alias);
		addField(pass);
		addField(mail);
		addField(fieldRol);
		
		GWT.setUncaughtExceptionHandler(new GWT.UncaughtExceptionHandler() {
		  @Override 
		  public void onUncaughtException(Throwable e) {
		    GWT.log(e.getMessage(), e); 
		  }
		});
	}
	
	@Override
	protected void executeFetch(final String requestId, DSRequest request,
								final DSResponse response) {
		
		final int startIndex = (request.getStartRow () < 0)?0:request.getStartRow ();
		final int endIndex = (request.getEndRow ()== null)?-1:request.getEndRow ();
		
		UserServiceAsync rpc = GWT.create(UserService.class);
		rpc.fetch(new AsyncCallback<List<User>>() {
			
			@Override
			public void onSuccess(List<User> result) {
				int size = result.size ();
                if (endIndex >= 0) {
                	if (endIndex < startIndex) {
                		size = 0;
                    }
                    else {
                        size = endIndex - startIndex + 1;
                    }
                }
                //Creamos los registros a devolver
				Record[] regs = new Record[result.size()];
				if (size > 0) {
					for (int i = 0; i < regs.length; i++) {
						Record record = new Record();
						copyValues(result.get(i), record);
						regs[i] = record;
					}
				}
				response.setData(regs);
				//IMPORTANTE: para que funcione el paginado debemos especificar
				//el total de registro del result set
				response.setTotalRows (result.size ());
				processResponse(requestId, response);
			}
			
			@Override
			public void onFailure(Throwable caught) {
				response.setStatus(RPCResponse.STATUS_FAILURE);
				processResponse(requestId, response);
			}
		});
	}

	@Override
	protected void executeAdd(final String requestId, final DSRequest request,
			final DSResponse response) {
		
		UserServiceAsync rpc = GWT.create(UserService.class);
		final ListGridRecord rec = new ListGridRecord (request.getData());
		rpc.create(rec.getAttribute("alias"), rec.getAttribute("pass"), 
					rec.getAttribute("mail"), rec.getAttribute(this.getDescription()), 
					new Long(rolSelectItem.getValue().toString()),
					new AsyncCallback<Void>() {

						@Override
						public void onFailure(Throwable caught) {
							response.setStatus(RPCResponse.STATUS_FAILURE);
							processResponse(requestId, response);							
						}

						@Override
						public void onSuccess(Void result) {
							
						}
					});
	}

	@Override
	protected void executeUpdate(final String requestId, final DSRequest request,
			final DSResponse response) {
		
		UserServiceAsync rpc = GWT.create(UserService.class);
		Record old = request.getOldValues();
		
		final ListGridRecord rec = new ListGridRecord (request.getData());
		rpc.update((rec.getAttribute("alias") == null) ? old.getAttribute("alias") : rec.getAttribute("alias"), 
				   (rec.getAttribute("pass") == null) ? old.getAttribute("pass") : rec.getAttribute("pass"), 
				   (rec.getAttribute("mail") == null) ? old.getAttribute("mail") : rec.getAttribute("mail"),
				   (rec.getAttribute(this.getDescription()) == null) ? old.getAttribute(getDescription()) : rec.getAttribute(this.getDescription()),
				   rolSelectItem.getDisplayValue(),
				   (rec.getAttributeAsBoolean(getFlagDelete()) == null) ? old.getAttributeAsBoolean(getFlagDelete()) : rec.getAttributeAsBoolean(getFlagDelete()),
				   (rec.getAttributeAsInt(getId()) == null) ? old.getAttributeAsInt(getId()) : rec.getAttributeAsInt(getId()),										 		
					new AsyncCallback<Void>() {

						@Override
						public void onFailure(Throwable caught) {
							response.setStatus(RPCResponse.STATUS_FAILURE);
							processResponse(requestId, response);							
						}

						@Override
						public void onSuccess(Void result) {
							
						}
					});
	}

	@Override
	protected void executeRemove(final String requestId, final DSRequest request,
								 final DSResponse response) {
		
		UserServiceAsync rpc = GWT.create(UserService.class);
		final ListGridRecord rec = new ListGridRecord (request.getData());		
		rpc.deleteUser(rec.getAttributeAsInt(getId()), new AsyncCallback<Void>() {

			@Override
			public void onFailure(Throwable caught) {
				response.setStatus(RPCResponse.STATUS_FAILURE);
				processResponse(requestId, response);
			}

			@Override
			public void onSuccess(Void result) {
				//executeFetch(requestId, request, response);
			}
		});
	}
	
	private void copyValues(User from, Record to) {
		to.setAttribute("alias", from.getAlias());
		to.setAttribute("pass", from.getPassword());
		to.setAttribute("mail", from.getMail());
		to.setAttribute("rol", from.getRol().getDescription());
		rolSelectItem.setDefaultValues(Long.toString(from.getRol().getId()));
		to.setAttribute(getDescription(), from.getDescription());
		to.setAttribute(getId(), from.getId());
		to.setAttribute(getAddDate(), from.getAddDate());
		to.setAttribute(getModDate(), from.getModDate());
		to.setAttribute(getFlagDelete(), from.getFlagDelete());		
	}

}
